﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Formats.Tar;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Xml;
using Windows.Storage.Streams;
using Wpf.Ui.Controls;
using WPFTools;

namespace CSharpToolWPF.Pages {
    /// <summary>
    /// PageAddProjectToNewSln.xaml 的交互逻辑
    /// </summary>
    public partial class PageAddProjectToNewSln : Page {
        private static PageAddProjectToNewSln page;
        public static PageAddProjectToNewSln Instance {
            get;
            set;
        }
        private TaskCompletionSource<bool> taskCompletionSource = new();
        private VCXXmlTools _vcxXmlTools = null;
        private string objectPRXBasePath = @"D:\VC\ObjectPRX 2024";
        private string slnBasePath = @"D:\VC\ObjectPRX 2024\sln";
        private Color colorAlert = Color.FromRgb(237, 87, 85);
        private Color colorWarning = Color.FromRgb(237, 173, 85);
        private Color colorOk = Color.FromRgb(167, 237, 85);
        public PageAddProjectToNewSln() {
            InitializeComponent();
            this.KeepAlive = true;
            Instance = this;
        }

        private void btnDoProcess_Click(object sender, RoutedEventArgs e) {
            string filter = "";
            if (checkBoxIsNewSln.IsChecked == true) {
                filter = "*.vcxproj";
            }
            else {
                filter = "*.vcproj";
            }
            var listProjectFilePaths = CommonFunc.GetFilePathListFromDragInRTB(rtbFileList, filter);

            foreach (var projectFilePath in listProjectFilePaths) {
                CommonFunc.ProcessNewCreatedProjectHeaderFile(rtbLog, Path.GetFileNameWithoutExtension(projectFilePath));
            }
        }

        private async void btnStart_Click(object sender, RoutedEventArgs e) {
            List<string> filePathList = new List<string>();
            foreach (Block blk in rtbFileList.Document.Blocks) {
                var para = blk as Paragraph;
                if (para == null) {
                    continue;
                }
                var run = para.Inlines.ElementAt(0) as Run;
                if (run == null) {
                    continue;
                }
                filePathList.Add(run.Text);
            }
            // 
            var listProjectNames = new List<string>();
            foreach (string path in filePathList) {
                if (File.Exists(path)) {
                    listProjectNames.Add(Path.GetFileNameWithoutExtension(path));
                }
                else if (Directory.Exists(path)) {
                    listProjectNames.Add(Path.GetFileName(path));
                }
                else {
                    Logger.WriteLog($"给出的路径：{path} 不存在！\n\n", rtbLog, Colors.Red);
                    return;
                }
            }
            // 
            SlnTools.AddProjectToSln(tbSlnPath.Text, listProjectNames);
            // 
            bool isNewSln = false;
            if (checkBoxIsNewSln.IsChecked == null) {
                isNewSln = false;
            }
            else {
                isNewSln = checkBoxIsNewSln.IsChecked.Value;
            }
            if (isNewSln) {
                Logger.WriteLog($"接下来请打开 VS，根据 VS 提示，重新加载解决方案，然后找到新添加的项目，他们现在应该是加载失败的状态，\n" +
                    $"在列表最下方，重新加载他们，转换完成后保存解决方案，在此按下回车，以替换 vcproj 到 vcxproj。\n\n", rtbLog);
                // 显示另一个按钮并暂停流程
                btnContinue.Visibility = Visibility.Visible;
                await taskCompletionSource.Task;
                taskCompletionSource = new TaskCompletionSource<bool> { };
                // 
                
                string content = File.ReadAllText(tbSlnPath.Text, Encoding.GetEncoding("gb2312"));
                var listAddedProjects = new List<string>();
                // 是否自动后处理
                if (checkBoxIsApplyPostProcess.IsChecked.Value) {
                    var matches = Regex.Matches(content, @"\w+\\\w+.vcproj");
                    // 
                    string patternWithExpMarco = @"^([\t ]*)class[ ]+(\w+)[ ]+(\w+)"; // 替换已经设置了的导入导出宏
                    string patternWithOutExpMacro = @"^([\t ]*)class[ ]+(\w+)[ ]+:"; // 给没有设置导入导出宏的，且有继承的类设置导入导出宏
                    string patternWithOutExpMacroAndDerives = @"^([\t ]*)class[ ]+(\w+)[\t ]*(\r?)$"; // 给没有设置导入导出宏的，且没有继承的类设置导入导出宏。（末尾的\r?$是C#在处理\r\n结尾时需要特定的操作，所以在替换的时候也要把\r加回去，不然就不统一了）
                    string patternShareHeader = @"^[\t ]*#define[ ]+(\w+)[ ]+_declspec"; // 用于在 ShareHeader 里查找对应的宏名称
                    // 
                    matches.ToList().ForEach(item => {
                        var projectPath = slnBasePath + @"\" + item.Value;
                        #region 更改编译器，添加VC目录等
                        // 虽然上面匹配的是vcproj，但是实际要修改的是其vcxproj
                        string vcProjectPath = projectPath.Replace(".vcproj", ".vcxproj");
                        var xmlDoc = new XmlDocument();
                        xmlDoc.Load(vcProjectPath);
                        // 
                        _vcxXmlTools.AfterTransferToNew(xmlDoc, checkBoxIsDeleteAllInputLib.IsChecked.Value);
                        // 
                        #endregion

                        #region 更改导入导出宏，以及给没有添加导入导出宏的类添加
                        CommonFunc.ProcessNewCreatedProjectHeaderFile(rtbLog, projectPath);
                        #endregion

                    });
                }
                string updatedContent = content.Replace(".vcproj", ".vcxproj");
                File.WriteAllText(tbSlnPath.Text, updatedContent);
            }
            else {
                Logger.WriteLog($"接下来请打开 VS，加载项目，使其刷新项目的 Hash。\n\n", rtbLog);
            }
        }
        private void rtbFileList_DragEnter(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                e.Effects = DragDropEffects.Copy;
            }
            else
                e.Effects = DragDropEffects.None;
            e.Handled = true;
        }

        private void btnPickSln_Click(object sender, RoutedEventArgs e) {
            var fileDialog = new OpenFileDialog();
            //fileDialog.FileName = "Document"; // Default file name
            fileDialog.DefaultExt = ".sln"; // Default file extension
            fileDialog.Filter = "VS Solution (.sln)|*.sln"; // Filter files by extension

            // Show open file dialog box
            bool? result = fileDialog.ShowDialog();
            string file = "";
            // Process open file dialog box results
            if (result == true) {
                // Open document
                file = fileDialog.FileName;
            }
            tbSlnPath.Text = file;
        }

        private void tbSlnPath_Drop(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                // 获取文件路径数组
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                // 清空 RichTextBox 内容
                rtbFileList.Document.Blocks.Clear();

                // 遍历文件路径并显示在 RichTextBox 中
                foreach (var file in files) {
                    Paragraph paragraph = new Paragraph(new Run(file));
                    rtbFileList.Document.Blocks.Add(paragraph);
                }
            }
        }

        private void btnContinue_Loaded(object sender, RoutedEventArgs e) {
            btnContinue.Visibility = Visibility.Collapsed;
        }

        private void btnContinue_Click(object sender, RoutedEventArgs e) {
            taskCompletionSource.SetResult(true);
            btnContinue.Visibility = Visibility.Collapsed;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e) {
            _vcxXmlTools = new VCXXmlTools(rtbLog);
        }
    }
}
